package neuronvisualizer;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

public class FileButtonListener implements ActionListener {
	private OptionBar parent;
	public FileButtonListener(OptionBar p){
		parent = p;
	}

	public void actionPerformed(ActionEvent e) {
		JFileChooser fileChooser = new JFileChooser();
		
		fileChooser.setFileFilter(new FileFilter(){

			@Override
			public boolean accept(File f) {
		        if (f.isDirectory()) {
		            return true;
		        }
		        String filename = f.getName();
		        
		        if (filename != null) {
		            if (filename.endsWith(".txt")) {
		                    return true;
		            } else {
		                return false;
		            }
		        }
		 
		        return false;
			}

			@Override
			public String getDescription() {
		        return "*.txt";
			}
				
		});
		fileChooser.setAcceptAllFileFilterUsed(false);
		int returnVal = fileChooser.showOpenDialog((Component) e.getSource());
		if(returnVal== JFileChooser.APPROVE_OPTION){
			File file = fileChooser.getSelectedFile();
			String tempPath = file.getAbsolutePath();
			if(tempPath.endsWith(".txt")){
				if(parent.getDriver().isInitialized()){
					parent.getDriver().disposeNeuronArray();
					parent.getDriver().loadNeurons(tempPath);
				}
				else{
					parent.getDriver().loadNeurons(tempPath);
					parent.getDriver().loadVisual();
					parent.enableOptions();					
				}
			}			
			else{
				JOptionPane.showMessageDialog(null, "Invalid file type, please load a .txt file!");
			}
		}//End of choosing neuron file
	}
}
